<template>
    <div class="wrapper" v-if="flag">

        <el-form :model="form" :rules="rules" label width=" 80px" class="login-box" status-icon
                 style="background-color: #fff;border-radius: 10px;position: relative;top:100px" ref="loginForm">
            <!--            <h3 class="login-title">欢迎登录</h3>-->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="密码登录" name="first">
                    <div v-show="showLoginType===1">
                        <el-form-item prop="username">
                            <el-input prefix-icon="el-icon-user" type="text" placeholder=" 请输入用户名"
                                      v-model="form.username"/>
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input prefix-icon="el-icon-lock" type="password" placeholder=" 请输入密码" show-password
                                      v-model=" form.password"/>
                        </el-form-item>
                        <div style="display: flex">
                            <el-form-item prop="checkcode">
                                <input type="hidden" v-model="form.checkcodekey">
                                <el-input size="medium" prefix-icon="iconfont icon-yanzhengyanzhengma"
                                          placeholder="请输入验证码"
                                          v-model="form.checkcode"
                                          style="width: 220px"></el-input>
                            </el-form-item>
                            <img @click="getCheckCode" style="flex: 1;margin-left: 10px;width: 70px;height: 40px"
                                 :src="checkcode_img"/>
                        </div>

                        <el-form-item>
                            <el-checkbox v-model="checked">30天自动登录</el-checkbox>
                        </el-form-item>
                        <el-form-item style="text-align: center">
                            <el-button style="width: 100%" type="primary" v-on:click="onSubmit('loginForm')">登录
                            </el-button>
                        </el-form-item>
                        <span>
<!--                <a href="http://localhost:8160/auth/oauth/login/wechat_open">-->
<!--                    <img src="../assets/img/weixin.png" width="40" height="40"/></a>-->
<!--                            &lt;!&ndash;                <a style="margin-left: 10px" href="javascript:void(0);">&ndash;&gt;-->
<!--                            &lt;!&ndash;                    <img src="../assets/img/QQ.png" width="40" height="40"/></a>&ndash;&gt;-->
<!--                <a style="margin-left: 10px" href="http://localhost:8160/auth/oauth/login/gitee"><img-->
<!--                        src="../assets/img/gitee.png" width="40" height="40"/></a>-->
                <el-link id="sign" style="position: relative;left: 290px;bottom:10px" type="primary"
                         v-on:click="$router.push('/register')">立即注册</el-link>
            </span>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="免密码登录" name="second">
                    <div v-show="showLoginType===2">
                        <el-form-item prop="email">
                            <el-autocomplete prefix-icon="el-icon-message" style="width: 100%"
                                             v-model="form.email"
                                             :fetch-suggestions="querySearchEmail"
                                             :trigger-on-focus="false"
                                             placeholder="接收邮件邮箱"
                            >
                            </el-autocomplete>
                        </el-form-item>

                        <!--                        <EmailInput/>-->
                        <div>
                            <el-form-item prop="checkcode">
                                <input type="hidden" v-model="form.checkcodekey">
                                <el-input size="medium" prefix-icon="iconfont icon-yanzhengyanzhengma"
                                          placeholder="请输入6位验证码"
                                          v-model="form.checkcode"
                                          style="width: 220px"></el-input>
                                <el-button style="float: right" :disabled="disabled" @click="getEmailCode">{{
                                        valiBtn
                                    }}
                                </el-button>
                            </el-form-item>
                        </div>
                        <el-form-item style="text-align: center">
                            <el-button style="width: 100%" type="primary" v-on:click="onSubmit('loginForm')">登录
                            </el-button>
                        </el-form-item>
                        <span>
<!--                <a href="http://localhost:8160/auth/oauth/login/wechat_open"><img src="../assets/img/weixin.png"-->
<!--                                                                                  width="40"-->
<!--                                                                                  height="40"/></a>-->
<!--                                            <a style="margin-left: 10px" href="javascript:void(0);"><img-->
<!--                                                    src="../assets/img/QQ.png" width="40"-->
<!--                                                    height="40"/></a>-->
<!--                <a style="margin-left: 10px" href="http://localhost:8160/auth/oauth/login/gitee"><img-->
<!--                        src="../assets/img/gitee.png" width="40" height="40"/></a>-->
                <el-link id="sign" style="position: relative;left: 290px;bottom:10px" type="primary"
                         v-on:click="$router.push('/register')">立即注册</el-link>
            </span>
                    </div>
                </el-tab-pane>
            </el-tabs>

        </el-form>
    </div>
</template>

<script>
    import {login, getCheckCodeSubmit, getEmailCodeSubmit, getToken, getPublicKey} from '@/api/login'
    import Cookies from 'js-cookie'
    import {encrypt, decrypt} from "@/utils/jsencrypt";
    import JSEncrypt from '@/utils/jsencryptmin.js'


    export default {
        name: "Login",
        data() {
            return {
                publicKey: '',
                roles: {},
                firstRoles: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                    ],
                    // checkcode: [{required: true, message: '验证码不可为空', trigger: 'blur'}],
                    // email: [
                    //     {required: true, message: '邮箱不能为空', trigger: 'change'},
                    //     {pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱'}
                    // ]
                },
                emailPattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$/,
                //请求后端的表单数据
                usernamejson: {
                    username: '',
                    grant_type: 'password',
                    client_secret: '112233',
                    client_id: 'client',
                },
                //请求后端的表单数据
                form: {
                    email: '',
                    username: Cookies.get('username') ? Cookies.get('username') : 'vip',
                    password: Cookies.get('password') ? decrypt(Cookies.get('password')) : 'vip',
                    checkcode: '',
                    checkcodekey: '',
                    authType: 'password'
                },
                checkcode_img: '', //验证码图片
                valiBtn: '获取验证码',
                disabled: false,//倒数60秒
                checked: false,//是否30天登录
                flag: true,//登录成功后台跳转到登录页就不显示登录组件
                showLoginType: 1,//切换登录方式
                activeName: 'first',
                // getcheckcodeflag: true, //防止频繁申请验证码
            }
        },
        methods: {
            onSubmit() {
                this.$refs['loginForm'].validate((valid) => {
                    if (valid) {  // 表单校验合法
                        if (this.showLoginType === 2) {
                            if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(this.form.email)) {
                                this.$message.error("请输入正确的邮箱")
                                return
                            } else if (this.form.checkcode === '') {
                                this.$message.error("请输入验证码")
                                return
                            }
                        }
                        this.$Loading("登录中...")
                        this.login()
                    } else {
                        return false;
                    }
                });
            },
            login() {
                //  var data = JSON.parse(JSON.stringify(this.form))
                //  var RSAencrypt = new JSEncrypt();
                // RSAencrypt.setPublicKey(this.publicKey);
                //  data.password = RSAencrypt.encrypt(data.password) //开始加密
                this.usernamejson.username = JSON.stringify(this.form)
                getToken(this.usernamejson).then(res => {
                    localStorage.setItem("token", res.access_token)
                    localStorage.setItem("refresh_token", res.refresh_token)
                    login().then(res => {
                        localStorage.setItem("user", JSON.stringify(res.data.user))
                        localStorage.setItem("menus", JSON.stringify(res.data.menus))
                        localStorage.setItem("permissions", JSON.stringify(res.data.permissions))
                        this.$Loading.close()
                        this.$router.replace("/home")
                        this.$message.success("登录成功")
                        this.$Loading.close()
                        if (this.checked) {
                            Cookies.set("username", this.form.username, {expires: 30})//设置30天
                            Cookies.set("password", encrypt(this.form.password), {expires: 30})
                            // Cookies.set("token", res.access_token, {expires: 30});//设置30天
                        } else {
                            // 否则移除
                            Cookies.remove("username")
                            Cookies.remove("password")
                            //Cookies.set("token", res.access_token, {expires: 1});//设置30天
                        }
                    })
                }).catch(err => {
                    this.$Loading.close()
                    this.form.checkcode = ''
                    this.form.checkcodekey = ''
                    this.getCheckCode()
                })

            },
            //获取邮箱验证码
            getEmailCode() {
                this.$refs['loginForm'].validateField('email', (err) => {
                    if (this.form.email===''|| this.form.email===null) {
                        this.$message.warning("请输入邮箱")
                        return;
                    } else {
                        // console.log('已通过')
                        getEmailCodeSubmit(this.form.email).then(res => {
                            console.log(res)
                        })
                        this.tackBtn();   //验证码倒数60秒
                    }
                })
            },
            //获取图片验证码
            getCheckCode() {
                // if (this.getcheckcodeflag) {
                getCheckCodeSubmit().then(res => {
                    //console.log(res)
                    if (res && res.aliasing) {
                        this.checkcode_img = res.aliasing
                        this.getcheckcodeflag = false
                        setTimeout(() => {
                            this.getcheckcodeflag = true
                        }, 10000)
                    }
                    if (res && res.key) {
                        this.form.checkcodekey = res.key
                    } else {
                        this.$message.error('加载验证码出错')
                    }
                })
                //   } else {
                //        this.$message.warning("请求太频繁")
                //    }
            },
            //验证码倒数60秒
            tackBtn() {
                let time = 300;
                let timer = setInterval(() => {
                    if (time == 0) {
                        clearInterval(timer);
                        this.valiBtn = '获取验证码';
                        this.disabled = false;
                    } else {
                        this.disabled = true;
                        this.valiBtn = time + '秒后重试';
                        time--;
                    }
                }, 1000);
            },
            //切换登录方式
            handleClick(tab) {
                if (tab.name === 'first') {
                    this.form.authType = 'password'
                    this.rules = this.firstRoles
                    this.showLoginType = 1
                } else if (tab.name === 'second') {
                    this.form.email = ""
                    console.log(this.form)
                    this.form.authType = 'email'
                    this.rules = {}
                    this.showLoginType = 2
                }

            },
            // 邮箱自动填充后缀名
            querySearchEmail(queryString, callback) {
                this.errorMsg = ''
                const emailList = [
                    {value: '@qq.com'},
                    {value: '@126.com'},
                    {value: '@163.com'},
                    {value: '@sina.com'},
                    {value: '@21cn.com'},
                    {value: '@sohu.com'},
                    {value: '@yahoo.com.cn'},
                    {value: '@tom.com'},
                    {value: '@etang.com'},
                    {value: '@eyou.com'},
                    {value: '@56.com'},
                    {value: '@x.cn'},
                    {value: '@chinaren.comsogou.com'},
                    {value: '@citiz.com'},
                ]
                let results = []
                let queryList = []
                emailList.map(item => {
                    queryList.push({value: queryString.split('@')[0] + item.value})
                })
                results = queryString ? queryList.filter(this.createFilter(queryString)) : queryList;
                callback(results);
            },
            // 邮箱填写过滤
            createFilter(queryString) {
                return (item) => {
                    return (item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },
            // init(){
            //     // if(Cookies.get("publicKey")){
            //     //     this.publicKey = Cookies.get("publicKey")
            //     //     return
            //     // }
            //     getPublicKey().then(res => {
            //         this.publicKey = res.data //公钥信息
            //        // Cookies.set("publicKey", res.data, { "expires": 30 })
            //     });
            // }
        },
        created() {
            //第三方登录，用户点击登录后，跳转到登录页，登录页面对路由进行判断，然后进行登录获取token
            let authType = this.$route.query.authType
            if (authType === 'wx' || authType === 'gitee' || authType === 'wechat_open') {
                this.form.authType = this.$route.query.authType
                this.form.unionId = this.$route.query.unionId
                this.login()
                this.flag = false
            } else {
                this.rules = this.firstRoles
                this.getCheckCode();//this.init()
                this.flag = true
            }

        },
    }
</script>

<style scoped>
    .wrapper {
        height: 100vh;
        background-image: linear-gradient(to bottom right, #FC466B, #3F5EFB);
        overflow: hidden;
    }

    .login-box {
        border: 1px solid #DCDFE6;
        width: 350px;
        margin: 50px auto;
        padding: 35px 35px 15px 35px;
        border-radius: 5px;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        box-shadow: 0 0 25px #909399;
    }

    .login-title {
        text-align: center;
        margin: 0 auto 40px auto;
        color: #303133;
    }

    .el-tabs >>> .el-tabs__item {
        font-weight: bold;
        font-size: 16px;
    }

    .el-tabs >>> .el-tabs__nav-wrap::after {
        background-color: white
    }

    #sign:hover {
        font-weight: bold;
        color: #1A73E8;
        border-bottom: white;
    }

    #emailcode:hover {
        font-weight: bold;
        color: #409EFF;
        border-bottom: white;
    }

    #sign {
        font-weight: bold;
        color: #1A73E8;
    }

</style>
